<template>
	<view class="movie-section">
		<!-- 顶部搜索区 -->
		<view class="search-header">
			<!-- <view class="city-select" @tap="selectCity">
				<image class="search-icon" :src="static_url + '/static/img/address.png'"></image>
				<text>{{ selectedCity }}</text>
			</view>
			<view class="" @click="allBtn">
				<text>{{allCity}}</text>
				<text class="arrow">▼</text>
			</view> -->
			<view class="selected-city">
				<uni-data-picker :localdata="items" :border="false" :placeholder="regiondata || '请选择城市'"
					@change="regionchange" ref="picker"></uni-data-picker>
			</view>
			<view class="search-box">
				<image class="search-icon" src="/static/img/search.png"></image>
				<input type="text" @input="onSearchBlur" v-model="searchKey" :placeholder="getSearchPlaceholder()"
					placeholder-class="placeholder" />
			</view>
		</view>
		<!-- 显示城市的区 -->
		<view class="show-city" v-if="showDistricts">
			<view class="show-city-item" v-for="(item, index) in districts" :key="index"
				:class="{ 'highlighted': selectedDistrictIndex === index }" @click="selectDistrict(item, index)">
				<text>{{ item.name }}</text>
			</view>
		</view>
		<!-- 顶部选项卡 -->
		<view class="tab-header">
			<view :style="{ color: currentTab == index ? t('color1') : '' }" v-for="(tab, index) in tabs" :key="index"
				class="tab-item" :class="{ active: currentTab == index }" @tap="switchTab(index)">
				{{ tab }}
				<view :style="{ backgroundColor: t('color1') }" class="active-curve"></view>
			</view>
		</view>

		<!-- 热映电影列表 -->
		<scroll-view v-if="currentTab == 0" class="movie-list" scroll-y>
			<view class="" v-if="filteredMovies.length > 0">
				<view class="movie-item" v-for="(item, index) in filteredMovies" :key="index"
					@tap.stop="goToDetail(item)">
					<view class="movie-poster">
						<image :src="item.poster" mode="aspectFill"></image>
					</view>
					<view class="movie-info">
						<view class="movie-sub">
							<view class="movie-top">
								<view class="movie-title">{{ item.title }}</view>

							</view>
							<view class="cinema-tags">
								<text class="tag" v-for="(tag, idx) in item.tags" :key="idx">{{ tag }}</text>
							</view>
							<view class="movie-score text-cut ">电影评分：<text class="text-col">{{ item.score }}</text>
							</view>
							<view class="movie-score text-cut ">导演：{{ item.director }}</view>
							<view class="movie-star text-cut ">主演：{{ item.star }}</view>
							<!-- <view class="movie-showinfo">今天{{item.how_many}}家影院放映{{ item.num }}场</view> -->
						</view>
						<view class="action-bottom">
							<view :style="{ backgroundColor: t('color1') }" class="action-button"
								@tap.stop="buyTicket(item)">购票</view>
						</view>
					</view>
				</view>
			</view>
			<view class="" v-else>
				<nodata></nodata>
			</view>
		</scroll-view>

		<!-- 影院列表 -->
		<scroll-view v-if="currentTab == 1" class="cinema-list" scroll-y>
			<view class="" v-if="filteredCinema.length > 0">
				<view class="cinema-item" v-for="(item, index) in filteredCinema" :key="index"
					@tap.stop="goToCinema(item)">
					<view class="cinema-info">
						<view class="cinema-name">{{ item.name }}</view>
						<view class="cinema-address">{{ item.address }}</view>
					</view>
					<view class="cinema-distance">{{ item.distance }}</view>
				</view>
			</view>
			<view class="" v-else>
				<nodata></nodata>
			</view>
		</scroll-view>

		<!-- 待映电影列表 -->
		<scroll-view v-if="currentTab == 2" class="movie-list" scroll-y>
			<view class="" v-if="filteredCome.length > 0">
				<view v-for="(item, index) in filteredCome" :key="index">
					<view class="text-xl">
						{{ item.publishDate }} <!-- 显示发布日期 -->
						<text class="text-day">{{ item.weekNumber }}</text> <!-- 显示星期 -->
					</view>

					<view v-for="(movie, movieIndex) in item.movies" :key="movieIndex" class="movie-item"
						@click.stop="toDetail(movie)">
						<view class="movie-poster">
							<image :src="movie.poster" mode="aspectFill"></image>
						</view>
						<view class="movie-info">
							<view class="movie-sub">
								<view class="movie-top">
									<view class="movie-title">
										{{ (movie.title == null || movie.title == undefined) ? '' : movie.title }}
									</view>
								</view>
								<view class="cinema-tags">
									<text class="tag" v-for="(tag, idx) in movie.tags" :key="idx">{{ tag }}</text>
								</view>
								<view class="movie-score text-cut ">电影评分：<text class="text-col">{{ (movie.score == null
									|| movie.score == undefined) ? '' : movie.score }}</text>
								</view>
								<view class="movie-score text-cut ">
									导演：{{ (movie.director == null || movie.director == undefined) ? '' : movie.director
									}}
								</view>
								<view class="movie-star text-cut ">
									主演：{{ (movie.star == null || movie.star == undefined) ? '' : movie.star }}</view>
							</view>
							<view class="action-bottom">
								<view class="action-button bg-blue" @tap.stop="toPresale(movie)">预售</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="" v-else>
				<nodata></nodata>
			</view>
		</scroll-view>
		<loading v-if="loading"></loading>
	</view>
</template>

<script>
var app = getApp()
export default {
	data() {
		return {
			selectedCity: '',
			searchKey: '',
			currentTab: 0,
			showDistricts: false,
			items: [],
			regiondata: '',
			districts: [],
			selectedDistrictIndex: 0,
			allCity: "全城",
			tabs: ['热映', '影院', '待映'],
			movieList: [],
			comeList: [],
			cinemaList: [],
			pagenum1: 1,
			pagenum2: 1,
			pagenum3: 1,
			loading: false,
			isload: false,
			longitude: null,
			latitude: null,
			cityName: '',
			areaName: '',
			filteredMovies: [],
			filteredCome: [],
			filteredCinema: [],
			opt: {}
		}
	},
	onPullDownRefresh: function () {
		var that = this;
		that.getHotList()
		that.getComeMovie()
		that.getLocation()
	},
	onReachBottom() {
		var that = this;
		if (that.currentTab == 0) {
			that.getHotList(this.pagenum1 + 1)
		}
		if (that.currentTab == 1) {
			this.getCinema(this.pagenum3 + 1)
		}
		if (that.currentTab == 2) {
			that.getComeMovie(this.pagenum2 + 1)
		}


	},
	onLoad(opt) {
		var that = this;
		if (opt) {
			that.currentTab = opt.active
			this.regiondata = uni.getStorageSync('city')

		}
		that.getHotList()
		that.getComeMovie()
		that.getCinema()
		uni.getLocation({
			type: 'wgs84', // 使用 wgs84 坐标系
			success: (res) => {
				console.log(res, 'res');
				const latitude = res.latitude; // 纬度
				const longitude = res.longitude; // 经度
				// 获取经纬度并更新数据
				this.latitude = res.latitude;
				this.longitude = res.longitude;
				this.getAreaByLocation(latitude, longitude)
				//this.getCityByLocation(latitude, longitude); // 使用经纬度获取城市名

			},
			fail: (err) => {
				// 获取位置失败
				console.log('获取位置失败:', err);

			}
		});
		// that.getLocation()
		// that.getCinema()

		app.get('Index/getCustom', {}, function (customs) {
			var url = app.globalData.static_url + '/static/area.json';
			uni.request({
				url: url,
				data: {},
				method: 'GET',
				header: {
					'content-type': 'application/json'
				},
				success: function (res2) {
					that.items = res2.data
				}
			});
		});
	},
	methods: {
		getSearchPlaceholder() {
			if (this.currentTab == 1) {
				return `搜索影院`
			} else {
				return `搜索影片`
			}
		},
		onSearchBlur() {
			// this.filterMovies();
			if (this.currentTab == 0) {
				app.get('film/get_hot_movie', {
					filmName: this.searchKey,

				}, (res) => {

					const data = res.data.movieList;
					if (res.status === 200) {
						this.filteredMovies = data

					} else {
						app.error(res.mgs)
					}


				});
			}
			if (this.currentTab == 1) {
				const cityName = uni.getStorageSync('cityName')
				const areaName = uni.getStorageSync('areaName')
				const longitude = uni.getStorageSync('longitude')
				const latitude = uni.getStorageSync('latitude')
				app.get('film/get_cinema', {
					cinemaName: this.searchKey,
					longitude: longitude,
					latitude: latitude,
					cityName: cityName,
					areaName: areaName
				}, (res) => {

					const data = res.data;
					if (res.status === 200) {
						this.filteredCinema = data

					} else {
						app.error(res.mgs)
					}


				});
			}
			if (this.currentTab == 2) {
				app.get('film/get_come_movie', {
					filmName: this.searchKey,

				}, (res) => {

					const data = res.data.screenedList;
					if (res.status === 200) {
						const data = res.data.screenedList;

						// 对电影列表按发布日期和星期分组
						const groupedData = data.reduce((acc, movie) => {
							const publishDate = movie.publishDate; // 获取发布日期
							const dateObj = new Date(publishDate);
							const weekNumber = dateObj.getDay(); // 获取星期（0-6）
							const key = `${publishDate}-${weekNumber}`; // 用日期和星期作为组合键

							if (!acc[key]) {
								acc[key] = {
									publishDate,
									weekNumber,
									movies: []
								};
							}
							acc[key].movies.push(movie); // 将电影加入对应的组合键下
							return acc;
						}, {});

						// 转换成符合格式的数据结构
						const groupedMovies = Object.keys(groupedData).map(key => {
							const {
								publishDate,
								weekNumber,
								movies
							} = groupedData[key];
							const weekNames = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
							return {
								publishDate,
								weekNumber: weekNames[weekNumber], // 显示星期名称
								movies,
							};
						});
						this.filteredCome = groupedMovies
					} else {
						app.error(res.mgs)
					}


				});
			}
		},
		// 过滤电影列表
		filterMovies() {
			const searchKey = this.searchKey.trim().toLowerCase(); // 获取去除空格并转为小写的搜索关键字
			if (this.currentTab == 0) {
				if (searchKey) {
					this.filteredMovies = this.filteredMovies.filter(movie =>
						movie.title?.toLowerCase().includes(searchKey)
					);
				} else {
					this.filteredMovies = this.movieList; // 如果搜索框为空，显示所有电影
				}
			} else if (this.currentTab == 1) {
				if (searchKey) {
					this.filteredCinema = this.filteredCinema.filter(movie =>
						movie.name?.toLowerCase().includes(searchKey)
					);
				} else {
					this.filteredCinema = this.cinemaList; // 如果搜索框为空，显示所有电影
				}
			} else if (this.currentTab == 2) {
				if (searchKey) {
					// 扁平化处理所有日期中的电影，并进行标题匹配
					this.filteredCome = this.filteredCome
						.map(day => ({
							...day,
							movies: day.movies.filter(movie =>
								movie.title?.toLowerCase().includes(searchKey.toLowerCase()) // 忽略大小写匹配
							)
						}))
						.filter(day => day.movies.length > 0); // 过滤掉没有电影的日期

				} else {
					this.filteredCome = this.comeList; // 如果搜索框为空，显示所有电影
				}

			}

		},



		getHotList(pagenum = 1) {
			this.pagenum1 = pagenum;
			this.loading = true;
			app.showLoading('加载中');
			app.get('film/get_hot_movie', {
				page: pagenum,
				limit: 10,
				filmName: this.searchKey,
			}, (res) => {
				this.loading = false;
				app.showLoading(false);
				if (res.status === 200) {

					this.filteredMovies = this.filteredMovies.concat(res.data.movieList);
				}

			});
			this.closeLoading()
		},
		getComeMovie(pagenum = 1) {
			// 更新当前页数
			this.pagenum2 = pagenum;

			// 设置加载状态
			this.loading = true;
			app.showLoading('加载中');
			// 调用API获取数据
			app.get('film/get_come_movie', {
				page: pagenum,
				limit: 10,
				filmName: this.searchKey
			}, (res) => {
				this.loading = false; // 请求完成，取消加载状态
				app.showLoading(false);
				if (res.status === 200) {
					const data = res.data.screenedList;

					// 对电影列表按发布日期和星期分组
					const groupedData = data.reduce((acc, movie) => {
						const publishDate = movie.publishDate; // 获取发布日期
						const dateObj = new Date(publishDate);
						const weekNumber = dateObj.getDay(); // 获取星期（0-6）
						const key = `${publishDate}-${weekNumber}`; // 用日期和星期作为组合键

						if (!acc[key]) {
							acc[key] = {
								publishDate,
								weekNumber,
								movies: []
							};
						}
						acc[key].movies.push(movie); // 将电影加入对应的组合键下
						return acc;
					}, {});

					// 转换成符合格式的数据结构
					const groupedMovies = Object.keys(groupedData).map(key => {
						const {
							publishDate,
							weekNumber,
							movies
						} = groupedData[key];
						const weekNames = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
						return {
							publishDate,
							weekNumber: weekNames[weekNumber], // 显示星期名称
							movies,
						};
					});

					this.comeList = this.comeList.concat(groupedMovies);

					// 筛选后的电影列表更新
					this.filteredCome = this.comeList;

				} else {
					// 错误处理，提示用户
					app.showToast('数据加载失败，请稍后再试');
				}

			});
			this.closeLoading()
		},



		// 获取用户位置信息
		getLocation() {
			uni.getLocation({
				type: 'wgs84', // 使用 wgs84 坐标系
				success: (res) => {
					console.log(res, 'res');
					const latitude = res.latitude; // 纬度
					const longitude = res.longitude; // 经度
					// 获取经纬度并更新数据
					this.latitude = res.latitude;
					this.longitude = res.longitude;
					this.getAreaByLocation(latitude, longitude)
					// this.getCityByLocation(latitude, longitude); // 使用经纬度获取城市名
					this.getCinema()
				},
				fail: (err) => {
					// 获取位置失败
					console.log('获取位置失败:', err);

				}
			});
		},

		getAreaByLocation(latitude, longitude) {
			app.get('address/getAreaByLocation', {
				latitude: latitude,
				longitude: longitude,
				type: 0,
			}, (res) => {
				if (res.status == 1) {
					const result = res;
					const city = `${result.province}/${result.city}/${result.district}`
					uni.setStorageSync('latitude', latitude)
					uni.setStorageSync('longitude', longitude)
					uni.setStorageSync('city', city)
					uni.setStorageSync('cityName', result.city)
					uni.setStorageSync('areaName', result.district)
					this.regiondata = city
				} else {
					app.error(res.msg)
				}

			});
		},

		// 使用腾讯逆地理编码 API 获取城市名
		getCityByLocation(latitude, longitude) {
			const key = '6E4BZ-3CCCW-RSGRQ-YKJ26-GETVT-FAFCV'; // 替换为你的腾讯位置服务 API Key
			const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${key}`;

			uni.request({
				url: url,
				success: (res) => {
					if (res.data.status === 0) {
						const result = res.data.result.address_component;
						const city = `${result.province}/${result.city}/${result.district}`
						uni.setStorageSync('latitude', latitude)
						uni.setStorageSync('longitude', longitude)
						uni.setStorageSync('city', city)
						uni.setStorageSync('cityName', result.city)
						uni.setStorageSync('areaName', result.district)
						this.regiondata = city
					} else {
						console.log('逆地理编码失败:', res.data.message);

					}
				},
				fail: (err) => {
					console.log('请求失败:', err);
				}
			});
		},
		getCinema(pagenum = 1) {
			this.loading = true;
			app.showLoading('加载中');
			const cityName = uni.getStorageSync('cityName')
			const areaName = uni.getStorageSync('areaName')
			const longitude = uni.getStorageSync('longitude')
			const latitude = uni.getStorageSync('latitude')
			this.pagenum3 = pagenum;
			app.get('film/get_cinema', {
				page: pagenum,
				limit: 10,
				longitude: longitude,
				latitude: latitude,
				cityName: cityName,
				areaName: areaName
			}, (res) => {
				this.loading = false;
				app.showLoading(false);
				const data = res.data;
				if (res.status === 200) {
					if (pagenum == 1) {
						this.filteredCinema = []
					}
					this.cinemaList = res.data
					this.filteredCinema = this.filteredCinema.concat(res.data);
				}
			});
			this.closeLoading()
		},


		closeLoading() {
			setTimeout(() => {
				app.showLoading(false);
			}, 8000)
		},

		regionchange(e) {
			const value = e.detail.value
			this.regiondata = value[0].text + ',' + value[1].text + ',' + value[2].text;
			uni.setStorageSync('city', this.regiondata)
			const city = value[1].text; // 获取选中的市
			const area = value[2].text; // 获取选中的区
			uni.setStorageSync('cityName', city); // 将城市信息存储到本地
			uni.setStorageSync('areaName', area); // 将区域信息存储到本地

			// 切换城市和区域后，重新请求影院数据
			this.getCinema(); // 重新加载第一页的数据
		},

		// 切换标签
		switchTab(index) {
			this.currentTab = index
			this.searchKey = ''
			this.filterMovies();

			if (this.currentTab === 0) {
				this.getHotList()
			}
			if (this.currentTab === 1) {
				this.getCinema()
			}
			if (this.currentTab === 2) {
				this.getComeMovie()
			}
		},

		// 跳转到电影详情
		goToDetail(movie) {
			uni.navigateTo({
				url: `/pagesZone/movie/movie_detail=${movie.id}`
			})
		},

		// 跳转到影院详情
		goToCinema(cinema) {
			uni.navigateTo({
				url: `/pagesZone/movie/cinema-detail?cinemaId=${cinema.id}`
			})
		},

		selectDistrict(item, index) {
			this.selectedDistrictIndex = index;
			this.allCity = item.name
			this.showDistricts = false
		},


		toDetail(item) {
			uni.navigateTo({
				url: './movie_detail?id=' + item.id
			})
		},
		// 购票
		buyTicket(movie) {
			uni.navigateTo({
				url: `/pagesZone/movie/movie_detail?filmId=${movie.id}&filmName=${movie.title}&type=1`
			})
		},
		//预售
		toPresale(item) {
			uni.navigateTo({
				url: `/pagesZone/movie/movie_detail?filmId=${item.id}&filmName=${item.title}&type=2`
			})
		}
	}
}
</script>

<style>
.movie-section {
	background: #fff;
	min-height: 100vh;
}

.search-header {
	display: flex;
	align-items: center;
	padding: 20rpx;
	background: #fff;
	position: relative;
}

.show-city {
	position: absolute;
	left: 0;
	z-index: 999;
	background-color: #fff;
	width: 100%;
	padding: 40rpx;
	display: flex;
	gap: 20rpx;
}

.show-city-item.highlighted {
	border-color: #ff3d5c;
}

.show-city-item {
	padding: 10rpx 20rpx;
	border: 1px solid #eee;
}

.city-select {
	display: flex;
	align-items: center;
	margin-right: 20rpx;
	font-size: 28rpx;
}

.selected-city {
	width: 40%;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	display: block;
	-webkit-line-clamp: 1;
	-webkit-box-orient: vertical;
	display: -webkit-box;

}

.arrow {
	font-size: 20rpx;
	margin-left: 6rpx;
	color: #666;
}

.search-box {
	flex: 1;
	display: flex;
	align-items: center;
	background: #f5f5f5;
	padding: 10rpx 20rpx;
	border-radius: 8rpx;
}

.search-icon {
	width: 32rpx;
	height: 32rpx;
	margin-right: 10rpx;
}

.placeholder {
	color: #999;
	font-size: 28rpx;
}

.tab-header {
	display: flex;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #eee;
}

.tab-item {
	flex: 1;
	text-align: center;
	font-size: 28rpx;
	color: #666;
	position: relative;
}

.tab-item.active {
	color: #ff6b81;
	font-weight: bold;
}

.tab-item.active .active-curve {
	content: '';
	position: absolute;
	bottom: -20rpx;
	left: 50%;
	transform: translateX(-50%);
	width: 40rpx;
	height: 4rpx;
}


.tab-item.active::after {
	content: '';
	position: absolute;
	bottom: -20rpx;
	left: 50%;
	transform: translateX(-50%);
	width: 40rpx;
	height: 4rpx;
	/* background: #ff6b81; */
}

.movie-list,
.cinema-list {
	padding: 20rpx;
}

.movie-item {
	display: flex;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
}

.movie-poster {

	width: 180rpx;
	height: 240rpx;
	margin-right: 20rpx;
	flex-shrink: 0;
}

.movie-poster image {
	width: 100%;
	height: 100%;
	border-radius: 8rpx;
}

.movie-score {
	color: #999;
	font-size: 24rpx;
	border-radius: 4rpx;
}

.movie-info {
	flex: 1;
	display: flex;
}

.movie-top {
	display: flex;
}

.text-cut {
	text-overflow: ellipsis;
	white-space: nowrap;
	overflow: hidden;
	padding: 10rpx 0;
}

.action-bottom {
	flex-shrink: 0;
	display: flex;
	align-items: center;
}

.movie-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-right: 10rpx;
}

.movie-star {
	font-size: 26rpx;
	color: #999;

}

.movie-showinfo {
	font-size: 24rpx;
	color: #666;
}

.action-button {
	width: 120rpx;
	height: 60rpx;
	line-height: 60rpx;
	text-align: center;
	background: #ff6b81;
	color: #fff;
	font-size: 28rpx;
	border-radius: 30rpx;
	margin-top: 10rpx;
}

.cinema-item {
	display: flex;
	justify-content: space-between;
	padding: 30rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
}

.cinema-info {
	flex: 1;
	margin-right: 20rpx;
}

.cinema-name {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 10rpx;
}

.cinema-address {
	font-size: 26rpx;
	color: #666;
	margin-bottom: 10rpx;
}

.cinema-tags {
	display: flex;
	flex-wrap: wrap;
	margin-top: 10rpx;
}

.tag {
	font-size: 22rpx;
	color: #999;
	padding: 4rpx 8rpx;
	border: 1rpx solid #eee;
	border-radius: 4rpx;
	margin-right: 10rpx;
	margin-bottom: 10rpx;
}

.cinema-price {
	font-size: 24rpx;
	color: #999;
}

.price {
	color: #ff6b81;
	font-size: 28rpx;
	font-weight: bold;
}

.cinema-distance {
	font-size: 24rpx;
	color: #999;
}

.text-col {
	color: #fe1d38;
}

.movie-sub {
	flex: 1;
	flex-shrink: 0;
	width: 380rpx;
}

.bg-blue {
	background-color: #0081ff;
}

.text-xl {
	background-color: #f0f0f0;
	font-size: 36rpx;
	padding: 10rpx 20rpx;
}

.text-day {
	font-size: 24rpx;
	margin-left: 10rpx;
}
</style>